<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getShops">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <!--可能出现一些没有及时激活的店铺 后面又想激活 联系管理员进行激活操作-->
				<el-form-item>
					<el-button type="primary" @click="handleActive" :disabled="this.sels.length===0">激活</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="50">
			</el-table-column>
			<el-table-column prop="companyName" label="名称" width="120" sortable>
			</el-table-column>
      <el-table-column prop="companyNum" label="联系电话" width="160" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: blue">待审核</span>
          <span v-if="scope.row.state==1" style="color: yellow">待激活</span>
          <span v-if="scope.row.state==2" style="color: green">激活成功</span>
          <span v-if="scope.row.state==3" style="color: red">驳回</span>
        </template>
      </el-table-column>
			<el-table-column prop="address" label="地址" width="200" sortable>
			</el-table-column>
			<el-table-column prop="admin.username" label="管理员" width="80" sortable>
			</el-table-column>
			<el-table-column prop="registerTime" label="注册时间" width="180" sortable>
			</el-table-column>
			<!--<el-table-column prop="sex" label="性别" width="100" :formatter="formatSex" sortable>
			</el-table-column>-->
			<el-table-column label="操作" width="220">
				<template scope="scope">
					<el-button size="small" @click="handleAudit(scope.$index, scope.row)" :disabled="scope.row.state!==1&&scope.row.state!==4">审核</el-button>
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增或编辑界面
		v-model="saveFormVisible" 老版本用
		:visible.sync 新版本用
		-->
		<el-dialog title="新增或编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="shop" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="名字" prop="name">
					<el-input v-model="shop.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="联系电话">
					<el-input type="textarea" v-model="shop.tel"></el-input>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="shop.address"></el-input>
				</el-form-item>
				<el-form-item label="logo">
					<el-input type="textarea" v-model="shop.logo"></el-input>
				</el-form-item>
        <el-form-item label="管理员" prop="manager">
          <el-select v-model="shop.admin" placeholder="请选择" value-key="id">
            <!--key唯一标识
                label选择之后显示到选择框中的值
                value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"-->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
    <!--注意 审核店铺信息 是没有权利修改内容的 所以全都是只读-->
		<el-dialog title="店铺注册信息" :visible.sync="auditFormVisible" :close-on-click-modal="false">
			<el-form :model="shop" label-width="80px">
				<el-form-item label="名字" prop="name">
					<el-input v-model="shop.name" auto-complete="off" :readonly="true"></el-input>
				</el-form-item>
				<el-form-item label="联系电话" prop="tel">
					<el-input v-model="shop.tel" auto-complete="off" :readonly="true"></el-input>
				</el-form-item>
        <el-form-item label="地址">
          <el-input type="textarea" v-model="shop.address" :readonly="true"></el-input>
        </el-form-item>
				<el-form-item label="logo">
					<el-input type="textarea" v-model="shop.logo" :readonly="true"></el-input>
				</el-form-item>
        <el-form-item label="管理员" prop="admin">
          <el-input v-model="shop.admin.username" auto-complete="off" :readonly="true"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="auditFormVisible = false">取消</el-button>
				<el-button type="warning" @click.native="disagreeSubmit" :loading="saveLoading">驳回</el-button>
				<el-button type="primary" @click.native="passSubmit" :loading="saveLoading">通过</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
			  query:{
          currentPage: 1,//当前页码
          pageSize:10,//每页显示多少条
          keyword:''//关键字
        },
        pageInfo:{
          total:0,//总数 默认是0
          rows:[],//页面数据
          totalPage:0//页面数据条数
        },
				listLoading: false,
				sels: [],//列表选中列

        //新增和编辑的数据
        shop:{//registerTime注册时间自动升生成
          id:null,
          name:'',
          tel:'',
          state:null,
          address:'',
          logo:'',
          admin: {}
        },
        employees:[],/*保存员工数据*/
				saveFormVisible: false,//新增或编译界面是否显示
        auditFormVisible: false,//审核信息框
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名字', trigger: 'blur' }
					]
				},

			}
		},
		methods: {
		  //手动激活 可能同时激活多个 就是再发送一次激活邮件
      handleActive(){
        let ids=[]//存放选中的id 传入后端的是一个数组
        for(let i=0;i<this.sels.length;i++){
          if(this.sels[i].state!=2){
            this.$message({
              message: '请选择处于待激活的店铺',
              type: 'error'
            })
            return;
          }

          ids.push(this.sels[i].id)
        }

        this.$http.patch("/sysmanage/tenant/active",ids)
            .then(result =>{
              if(result.data.success){
                this.$message({
                  message: '激活邮件发送成功!',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: result.data.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              this.$message({
                message: '操作异常!'+result.message,
                type: 'error'
              })
            })
      },
		  //审核通过
      passSubmit(){
        let para = Object.assign({}, this.shop);
        this.$http.post("/sysmanage/tenant/passAudit",para).then((result) => {
          if(result.data.success){
            this.$message({
              message: '操作成功!',
              type: 'success'
            });
          }
          else{
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }
        })
        .catch(result=>{
          this.$message({
            message: '操作异常!'+result.message,
            type: 'error'
          })
        })
        this.auditFormVisible = false;
      },
		  //审核驳回
      disagreeSubmit(){
        let para = Object.assign({}, this.shop);
        this.$http.post("/sysmanage/tenant/disagreeAudit",para).then((result) => {
          if(result.data.success){
            this.$message({
              message: '操作成功!',
              type: 'success'
            });
          }
          else{
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }
        })
        .catch(result=>{
          this.$message({
            message: '操作异常!'+result.message,
            type: 'error'
          })
        });
        this.auditFormVisible = false;
      },
		  //手动审核
      handleAudit(index,row){
        /*弹出框 显示店铺注册信息，审核人员判断是否有违规
         * 只有两个操作 通过或驳回
         * 通过还需要进行邮箱激活验证*/
        //回显
        this.shop = Object.assign({}, row);
        this.auditFormVisible = true;
      },
		  //获取员工
		  getEmployees() {
        this.$http.get("/employee")
            .then(result=>{
              result = result.data
              if(result.success){
                this.employees = result.resultObj;
              }else {
                this.$message({
                  message: '获取数据失败！'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              console.log("出错了"+result.message)
            })
      },
      //性别显示转换
			/*formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.se.x == 0 ? '女' : '未知';
			},*/
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getShops();
			},
			//获取部门列表
			getShops() {
				this.listLoading = true;
				this.$http.post("/sysmanage/tenant/list",this.query)
                  .then(result=>{
                    result = result.data
                    if(result.success){
                      this.pageInfo.total = result.total;
                      // this.shops = result.data.shops;
                      this.pageInfo=result.resultObj
                    }else {
                      this.$message({
                        message: '获取分页数据失败！'+result.message,
                        type: 'error'
                      });
                    }
                    this.listLoading = false;
                  })
                  .catch(result=>{
                    console.log("出错了"+result.message)
                  })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
          let id = row.id;
					this.$http.delete("/sysmanage/tenant/"+id)
              .then(result => {
                //NProgress.done();
                result = result.data
                if(result.success){
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else{
                  this.$message({
                    message: '删除失败',
                    type: 'error'
                  });
                }
                this.getShops();
                this.listLoading=false
              })
              .catch(result=>{
                this.$message({
                  message: '异常',
                  type: 'error'+result.message
                });
              })
				}).catch(() => {
          this.$message({
            message: '取消成功',
            type: 'error'
          });
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			  //回显
        this.shop = Object.assign({}, row);
        this.getEmployees();//获取员工数据
        let path = this.shop.path; //完整的path 包含自己的
        if (path){
          console.log(path);
          let paths = path.split("/"); //根据/分割
          let idsStr = paths.slice(1,paths.length-1);//最后一个是自己 不要
          let idsInt = [];
          for (let i = 0; i <idsStr.length ; i++) {//封装成数组
            idsInt.push(parseInt(idsStr[i]));
          }
          console.log(idsInt);
          //做部门的回显
          this.shop.parent = idsInt;//这里部门就变成了一个数组
        }
        this.saveFormVisible = true;
			},
			//显示新增界面
			handleAdd: function () {
			  //清空
        this.shop={
          id:null,
          name:'',
          tel:'',
          state:null,
          address:'',
          logo:'',
          admin: {}
        }

        this.getEmployees();//获取员工数据
				this.saveFormVisible = true;
			},
			//保存
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.shop);
              //把数据转换成我们想要格式 parent: [1, 2]---》parent:{id:2} 只需要一个上级部门id 不需要爷爷级的
              if (para.parent){
                let parentIds = para.parent; // [1, 2]
                let parentId = parentIds[parentIds.length-1]; // 2
                para.parent = {"id":parentId} //parent:{id:2}
              }

							// para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							this.$http.put("/sysmanage/tenant",para)
                  .then(result => {
                    result = result.data
                    if(result.success){

                      //NProgress.done();
                      this.$message({
                        message: '保存成功',
                        type: 'success'
                      })
                      this.$refs['saveForm'].resetFields();//重置表单
                      this.getShops();//保存完重新获取部门数据
                      this.saveFormVisible = false;//关闭对话框
                    }else{
                      this.$message({
                        message: '保存失败',
                        type: 'error'
                      })
                    }
                  })
                  .catch(result=>{
                    this.$message({
                      message: '保存失败',
                      type: 'error'+result.message
                    })
                  });
                this.saveLoading = false;//关闭加载条
							});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			  let ids=[]//存放选中的id 传入后端的是一个数组
			  for(var i=0;i<this.sels.length;i++){
			    ids.push(this.sels[i].id)
        }
			  // console.log(ids)

				// var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = {ids: ids};
					this.$http.patch("/sysmanage/tenant",ids)
              .then(result => {
                result = result.data
                this.listLoading = false;
                //NProgress.done();
                if(result.success){
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else {
                  this.$message({
                    message: '删除失败',
                    type: 'error'+result.message
                  });
                }
                this.getShops();
              });
				}).catch(() => {
				});
			}
		},
		mounted() {
			this.getShops();
		}
	}

</script>

<style scoped>

</style>